{% extends 'dashboard/base.html' %}
{% load static %}

{% block title %}奖品管理 - 后台管理{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">奖品管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <a href="{% url 'dashboard:reward_exchange_management' %}" class="btn btn-sm btn-outline-primary me-2">
            <i class="bi bi-clock-history"></i> 兑换记录
        </a>
        <button class="btn btn-sm btn-primary" onclick="showCreateRewardModal()">
            <i class="bi bi-plus-circle"></i> 添加奖品
        </button>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-primary h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            奖品总数</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ total_rewards }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-gift fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-success h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            启用中</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ active_rewards }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-check-circle fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-warning h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            已售罄</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ out_of_stock_rewards }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-exclamation-triangle fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stats-card border-start-info h-100">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            总兑换数</div>
                        <div class="h3 mb-0 font-weight-bold text-gray-800">{{ total_exchanges }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-cart-check fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 搜索和筛选 -->
<div class="card shadow mb-4">
    <div class="card-body">
        <form method="get" class="row g-3">
            <div class="col-md-4">
                <input type="text" name="search" class="form-control" placeholder="搜索奖品名称、描述..." value="{{ search_query }}">
            </div>
            <div class="col-md-3">
                <select name="type" class="form-select">
                    <option value="">所有类型</option>
                    <option value="coupon" {% if type_filter == 'coupon' %}selected{% endif %}>优惠券</option>
                    <option value="privilege" {% if type_filter == 'privilege' %}selected{% endif %}>平台特权</option>
                    <option value="physical" {% if type_filter == 'physical' %}selected{% endif %}>实物奖品</option>
                </select>
            </div>
            <div class="col-md-3">
                <select name="status" class="form-select">
                    <option value="">所有状态</option>
                    <option value="active" {% if status_filter == 'active' %}selected{% endif %}>启用中</option>
                    <option value="inactive" {% if status_filter == 'inactive' %}selected{% endif %}>已禁用</option>
                    <option value="out_of_stock" {% if status_filter == 'out_of_stock' %}selected{% endif %}>已售罄</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary me-2">
                    <i class="bi bi-search"></i> 搜索
                </button>
                <a href="{% url 'dashboard:rewards_management' %}" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-clockwise"></i> 重置
                </a>
            </div>
        </form>
    </div>
</div>

<!-- 奖品列表 -->
<div class="card shadow">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>奖品信息</th>
                        <th>类型</th>
                        <th>所需积分</th>
                        <th>库存</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for reward in rewards %}
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                {% if reward.image %}
                                <img src="{{ reward.image.url }}" alt="{{ reward.name }}"
                                     class="rounded me-2" width="50" height="50" style="object-fit: cover;">
                                {% else %}
                                <div class="rounded bg-light d-flex align-items-center justify-content-center me-2"
                                     style="width: 50px; height: 50px;">
                                    <i class="bi bi-gift text-muted"></i>
                                </div>
                                {% endif %}
                                <div>
                                    <strong>{{ reward.name }}</strong>
                                    <br>
                                    <small class="text-muted">{{ reward.description|truncatewords:10 }}</small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="badge bg-{% if reward.type == 'coupon' %}warning{% elif reward.type == 'privilege' %}info{% else %}success{% endif %}">
                                {{ reward.get_type_display }}
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-primary">{{ reward.points_required }}</span>
                        </td>
                        <td>
                            {% if reward.stock > 10 %}
                                <span class="badge bg-success">{{ reward.stock }}</span>
                            {% elif reward.stock > 0 %}
                                <span class="badge bg-warning">{{ reward.stock }}</span>
                            {% else %}
                                <span class="badge bg-danger">售罄</span>
                            {% endif %}
                        </td>
                        <td>
                            {% if reward.is_active %}
                                <span class="badge bg-success">启用</span>
                            {% else %}
                                <span class="badge bg-secondary">禁用</span>
                            {% endif %}
                        </td>
                        <td>{{ reward.created_at|date:"Y-m-d H:i" }}</td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-primary"
                                        onclick="showEditRewardModal({{ reward.id }})">
                                    <i class="bi bi-pencil"></i> 编辑
                                </button>
                                <button class="btn btn-outline-danger"
                                        onclick="deleteReward({{ reward.id }}, '{{ reward.name }}')">
                                    <i class="bi bi-trash"></i> 删除
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="bi bi-gift text-muted display-4"></i>
                            <p class="text-muted mt-2">暂无奖品数据</p>
                            <button class="btn btn-primary" onclick="showCreateRewardModal()">
                                <i class="bi bi-plus-circle"></i> 添加第一个奖品
                            </button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 创建/编辑奖品模态框 -->
<div class="modal fade" id="rewardModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rewardModalTitle">添加奖品</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="rewardForm">
                <div class="modal-body">
                    <input type="hidden" name="reward_id" id="rewardId">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">奖品名称</label>
                                <input type="text" name="name" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">奖品类型</label>
                                <select name="type" class="form-select" required>
                                    <option value="coupon">优惠券</option>
                                    <option value="privilege">平台特权</option>
                                    <option value="physical">实物奖品</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">奖品描述</label>
                        <textarea name="description" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">所需积分</label>
                                <input type="number" name="points_required" class="form-control" min="1" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">库存数量</label>
                                <input type="number" name="stock" class="form-control" min="0" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="is_active" class="form-check-input" id="isActive" checked>
                            <label class="form-check-label" for="isActive">启用此奖品</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function showCreateRewardModal() {
    document.getElementById('rewardModalTitle').textContent = '添加奖品';
    document.getElementById('rewardForm').reset();
    document.getElementById('rewardId').value = '';
    const modal = new bootstrap.Modal(document.getElementById('rewardModal'));
    modal.show();
}

function showEditRewardModal(rewardId) {
    fetch(`/dashboard/rewards/${rewardId}/edit/`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const reward = data.reward;
            document.getElementById('rewardModalTitle').textContent = '编辑奖品';
            document.getElementById('rewardId').value = reward.id;
            document.querySelector('input[name="name"]').value = reward.name;
            document.querySelector('select[name="type"]').value = reward.type;
            document.querySelector('textarea[name="description"]').value = reward.description || '';
            document.querySelector('input[name="points_required"]').value = reward.points_required;
            document.querySelector('input[name="stock"]').value = reward.stock;
            document.querySelector('input[name="is_active"]').checked = reward.is_active;

            const modal = new bootstrap.Modal(document.getElementById('rewardModal'));
            modal.show();
        } else {
            showAlert('获取奖品信息失败', 'error');
        }
    });
}

function deleteReward(rewardId, rewardName) {
    if (confirm(`确定要删除奖品 "${rewardName}" 吗？此操作不可恢复！`)) {
        fetch(`/dashboard/rewards/${rewardId}/delete/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('奖品删除成功', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(data.message, 'error');
            }
        });
    }
}

document.getElementById('rewardForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);
    const rewardId = formData.get('reward_id');
    const url = rewardId ? `/dashboard/rewards/${rewardId}/edit/` : '/dashboard/rewards/create/';

    fetch(url, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token }}',
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(rewardId ? '奖品更新成功' : '奖品创建成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('rewardModal')).hide();
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('网络错误，请重试', 'error');
    });
});

function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        <i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.querySelector('main').insertBefore(alertDiv, document.querySelector('main').firstChild);
    
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}
</script>
{% endblock %}